<template>
  <Header />
  <!-- changeBoxWidth 把宽改为 350px right 宽改为 0 -->
  <div class="content">
    <div class="login" :class="[changeBoxWidth ? 'login-change' : '',isShowLogin==4?'show-register':'']">
      <div class="left" :style="isShowLogin==4?'width: 100%':''">
        <!-- 登录 -->
        <div v-if="isShowLogin === 1" class="login-box">
          <!-- 切换登录方式 -->
          <div class="login-text">
            <span @click="switchingLoginMode = 1" :class="switchingLoginMode === 1 ? 'active' : ''">短信登录</span>
            <span @click="switchingLoginMode = 2" :class="switchingLoginMode === 2 ? 'active' : ''">账号登录</span>
          </div>
          <div class="login-form">
            <!-- 登录/注册 -->
            <el-form v-if="switchingLoginMode == 1" ref="loginFormRef" :model="codeLogin" :rules="formCodeRules"
              class="form-code" size="large" style="max-width: 320px">
              <el-form-item prop="phone" class="userName">
                <el-input v-model="codeLogin.phone" placeholder="请输入手机号或邮箱"></el-input>
              </el-form-item>
              <el-form-item prop="code" class="code">
                <el-input v-model="codeLogin.code" placeholder="请输入验证码"></el-input>
                <div @click="gotCode" class="get-code-btn">
                  <span :style="{ color: isGetCodeStatus ? '#ddd' : '#0497ff' }">{{
                    isGetCodeStatus ? `${getCodeCountTime}s后重新获取` : "获取短信验证码"
                    }}</span>
                </div>
              </el-form-item>
              <el-form-item>
                <!-- <el-checkbox size="small" style="margin-top: 10px">
                <span style="color: #ccc">登录即代表同意</span>
                <span>《xxx协议》《隐私协议》</span>
              </el-checkbox> -->
                <el-button @click="login" style="width: 320px; margin-top: 40px">登录/注册</el-button>
              </el-form-item>
            </el-form>
            <!-- 账号登录 -->
            <el-form v-if="switchingLoginMode == 2" :model="pswLogin" :rules="formPawRules" ref="pswLoginFormRef"
              class="form-user" size="large" style="max-width: 320px">
              <el-form-item prop="userName">
                <el-input v-model="pswLogin.userName" placeholder="请输入手机号或邮箱"></el-input>
              </el-form-item>
              <el-form-item prop="psw">
                <el-input v-model="pswLogin.psw" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item>
                <!-- <el-checkbox size="small" style="margin-top: 10px">
                <span style="color: #ccc">登录即代表同意</span>
                <span>《xxx协议》《隐私协议》</span>
              </el-checkbox> -->
                <el-button @click="pswLoginSubmit" style="width: 320px; margin-top: 40px">登录</el-button>
              </el-form-item>
              <el-form-item class="bom-text-btn">
                <el-button @click="goToForm(3, true)" type="text">成为组织者账号</el-button>
                <el-button @click="router.push({ path: '/login', query: { isReg: true}})" type="text">还没有账户？立即注册</el-button>
              </el-form-item>
              <el-form-item class="bom-text-btn">
                <div></div>
                <el-button @click="goToForm(2, true)" type="text">忘记密码?</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!-- 忘记密码 -->
        <AccountProcessing v-if="isShowLogin === 2" title="忘记密码" :isShowLogin="isShowLogin" @backToLogin="goToForm" />
        <AccountProcessing v-if="isShowLogin === 3" title="成为组织者账号" :isShowLogin="isShowLogin" @backToLogin="goToForm" />
        <Register style="width: 100%;" v-if="isShowLogin==4" title="注册账户" @backToLogin="goToForm"></Register>
      </div>
      <!-- 扫码登入 -->
      <ScanLogin/>
    </div>
  </div>
  <Footer />
</template>

<script setup lang="ts">
import { reactive,watch, ref, computed, onMounted } from "vue";
import type { FormRules } from "element-plus";
import ScanLogin from "@/components/login/ScanLogin.vue";
import AccountProcessing from "@/components/login/AccountProcessing.vue";
import Register from "@/components/login/Register.vue";
import { sendValidateCode, register, getLoginUserInfo, emailReister, sendEmailValidateCode } from "@/api/user";
import useUserStore from "@/stores/user";
import type { RegisterParams } from "@/types/user";
import { ElMessage } from "element-plus";
import { useRouter,useRoute } from "vue-router";
const router = useRouter();
const route = useRoute()
const userStore = useUserStore();
// 切换登录表单  1 : 验证码 2：账号
let switchingLoginMode = ref(1);
// false login宽为 700 true login宽为 350
let changeBoxWidth = ref(false);
// 切换表单 1 登录 2 忘记密码 3 成为组织者
let isShowLogin = ref<number>(1);
/**
 * 切换表单
 * index 1: 登录 2：忘记密码 3：成为组织者 4：注册用户
 * boo false login宽为 700 true login宽为 350
 */
const goToForm = (index: number, boo: boolean): void => {
  changeBoxWidth.value = boo;
  isShowLogin.value = index;
};


/**
 * 登录或注册
 */
const loginFormRef = ref<any>(null);
const codeLogin = reactive<RegisterParams>({
  code: "",
  phone: "",
});
const verifyMobilePhoneNumber = ({ }, value: any, callback: any) => {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (/^1[3-9]\d{9}$|^17[0-28]\d{8}$/.test(value) || emailRegex.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确的手机号或邮箱"));
  }
};
const formCodeRules = reactive<FormRules<RegisterParams>>({
  code: [{ required: true, message: "请输入验证码", trigger: ["blur", "change"] }],
  phone: [
    {
      required: true,
      message: "请输入电话号码或邮箱",
      trigger: ["blur", "change"],
    },
    { validator: verifyMobilePhoneNumber, trigger: ["blur", "change"] },
  ],
});

const login = () => {
  if (!loginFormRef) return;
  loginFormRef.value.validate(async (valid: RegisterParams) => {
    if (valid) {
      // 邮箱 注册
      if (codeLogin.phone.includes("@")) {
        let emailRes = await emailReister({
          email: codeLogin.phone,
          code: codeLogin.code,
        });
        if (emailRes.data.msg === "该邮箱已注册!") {
          // 邮箱已注册 直接登录
          // router.push("/");
          let loginRes = await userStore.loginByEmail({
            phoneOrEmail: codeLogin.phone,
            code: codeLogin.code,
          });
          // 登入成功
          if (loginRes.data.code === 200) {
            ElMessage({ message: "登入成功", type: "success" });
            router.push("/");
          } else {
            // 登入失败
            ElMessage({ message: "登入失败", type: "error" });
          }
        } else {
          ElMessage({ message: "注册成功 请重新登录", type: "success" });
        }
        return;
      }
      // 手机号注册
      let registerRes = await register({
        code: codeLogin.code,
        phone: codeLogin.phone,
      });
      // 因为后端接口分开了  如果注册了 那就登入
      if (registerRes.data.msg === "该手机号已注册!") {
        let loginRes = await userStore.login({
          code: codeLogin.code,
          phoneOrEmail: codeLogin.phone,
        });
        // 登入成功
        if (loginRes.data.code === 200) {
          ElMessage({ message: "登入成功", type: "success" });
          router.push("/");
        } else {
          // 登入失败
          ElMessage({ message: "登入失败", type: "error" });
        }
        return;
      }
      // 注册成功
      if (registerRes.data.code === 200) {
        ElMessage({
          message: "注册成功请重新登录",
          type: "success",
        });
      } else {
        // 注册失败
        ElMessage({
          message: registerRes.data.msg,
          type: "error",
        });
      }
    } else {
      return false;
    }
  });
};
let getCodeCountTime = ref(60);

const gotCode = async () => {
  if (!loginFormRef.value) return;
  loginFormRef.value.validateField("phone", async (errorMsg: boolean) => {
    if (errorMsg) {
      if (getCodeCountTime.value !== 60) return;
      let time = setInterval(() => {
        getCodeCountTime.value--;
        if (getCodeCountTime.value === 0) {
          clearTimeout(time);
          getCodeCountTime.value = 60;
        }
      }, 1000);
      let res;
      // 邮箱验证码
      if (codeLogin.phone.includes("@")) {
        res = await sendEmailValidateCode(codeLogin.phone);
      } else {
        res = await sendValidateCode(codeLogin.phone);
      }
      if (res.data.code === 200) {
        // 开启倒计时
        ElMessage({ message: res.data.msg, type: "success" });
        return;
      }
      ElMessage({ message: res.data.msg, type: "error" });
    } else {
      return false;
    }
  });
};

const isGetCodeStatus = computed(() => {
  return getCodeCountTime.value >= 1 && getCodeCountTime.value < 60;
});

onMounted(() => {
  // 是否注册：true为注册；false为登录
  // true则直接跳转到注册页面
  let isReg = route.query.isReg == undefined? false: route.query.isReg;
  isReg = isReg == "true"? true: false;
  console.log("是否注册：",isReg);
  if(isReg){
    console.log("跳转注册");
    goToForm(4, true)
  }
});
watch(
  () => route.query.isReg,
  (newVal, oldVal) => {
    if(newVal == "true"){
      console.log("监听跳转...");
      goToForm(4, true)
    }else{
      console.log("监听跳转...登录");
      goToForm(1, false)
    }
  }
)

/**
 * 密码登录
 */
interface pswLoginType {
  psw: string;
  userName: string;
}
const pswLogin = reactive<pswLoginType>({
  psw: "123456",
  userName: "15173020822",
});
const formPawRules = reactive<FormRules<pswLoginType>>({
  psw: [
    {
      required: true,
      message: "请输入密码",
      trigger: ["blur", "change"],
    },
  ],
  userName: [{ validator: verifyMobilePhoneNumber, trigger: ["blur", "change"] }],
});
let pswLoginFormRef = ref<any>(null);
const pswLoginSubmit = () => {
  if (!pswLoginFormRef.value) return;
  pswLoginFormRef.value.validate(async (valid: pswLoginType) => {
    if (!valid) {
      return false;
    }
  });
  userStore
    .pswLogin({
      phoneOrEmail: pswLogin.userName,
      password: pswLogin.psw,
    })
    .then(res => {
      if (res.data.code === 200) {
        ElMessage({ message: res.data.msg, type: "success" });
        router.push("/index");
        userStore.getUserInfo();
      } else {
        ElMessage({ message: res.data.msg, type: "error" });
      }
    });
};
</script>

<style lang="scss" scoped>
* {
  margin: 0;
}

:deep(.el-form-item__error) {
  top: 10%;

}
.login.show-register{
  width: 750px !important;
  height: 500px;
  margin-bottom: 10px;
}
.content {
  padding: 30px 0px;
}
.footer{
  width: 100%;
  padding: 40px 0;
}
.login {
  display: flex;
  margin: 90px auto 90px;
  padding: 30px 20px;
  justify-content: center;
  box-sizing: border-box;
  background-color: white;
  box-shadow: 0px 5px 10px 0px rgba(0, 0, 0, 0.1);
  width: 750px;
  height: 420px;
  // transition: width 0.8s;
  transition: all .8s;
  font-family: "微软雅黑";
  overflow: hidden;

  // 登录
  .left {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 450px;

    .login-box {
      .login-text {
        display: flex;
        justify-content: center;
        color: #a9a9a9;
        font-weight: 600;
        font-size: 18px;

        // 激活的样式
        .active {
          color: #000;

          &::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 30px;
            height: 4px;
            background-color: $main-color;
            border-radius: 10px;
          }
        }
      }

      .login-text span {
        position: relative;
        padding: 20px 21px;
        cursor: pointer;
      }

      .login-form {
        position: relative;

        // 验证码登录的样式
        .form-code {
          .userName {
            :deep(.el-form-item__content) {
              div:nth-child(1) {
                margin-top: 30px;
              }

              div:nth-child(2) {
                div:nth-child(1) {
                  // padding-right: 120px;
                }
              }
            }

            :deep(.el-form-item__content div:nth-child(1) .el-input__wrapper) {
              // padding-left: 100px;
              margin-top: 0;
            }
          }

          .code {
            :deep(.el-form-item__content) {
              div:nth-child(1) {
                margin-top: 30px;
              }

              div:nth-child(2) {
                div:nth-child(1) {
                  padding-right: 120px;
                }
              }
            }

            :deep(.el-form-item__content div:nth-child(1) .el-input__wrapper) {
              padding-left: 10px;
              margin-top: 0;
            }
          }
        }

        // 账号登录
        .form-user {
          :deep(.el-form-item__content) {
            div:nth-child(1) {
              margin-top: 30px;
            }

            div:nth-child(2) {
              div:nth-child(1) {
                padding-right: 10px;
              }
            }

            .forget-btn {
              position: absolute;
              right: 0;
              bottom: -40px;
            }
          }

          :deep(.el-form-item__content div:nth-child(1) .el-input__wrapper) {
            padding-left: 10px;
            margin-top: 0;
          }

          .bom-text-btn {
            :deep(.el-form-item__content) {
              display: flex;
              justify-content: space-between;

              .el-button--large {
                padding: 0;
              }
            }
          }
        }

        .number-area {
          position: absolute;
          left: 10px;
          top: 42px;
          z-index: 999;
          font-size: 12px;

          span {
            margin-right: 10px;
          }
        }

        .get-code-btn {
          position: absolute;
          left: 220px;
          top: 30px;
          z-index: 999;
          font-size: 12px;
          cursor: pointer;
          color: $main-color;
        }
      }
    }
  }
}

// 过度切换的类
.login-change {
  width: 500px !important;

  .right {
    width: 0 !important;

    .right-box {
      border-left: none !important;
    }
  }
}
</style>
